<?php
Modulator()->registerFilter('html_output', 'parseWikiMarkup');

function parseWikiMarkup($html) {
	// Format is {optional type:Content Title|Optional alternate text}
	
	preg_match_all(':\{+[^\}\n]+\}:', $html, $matches);
	
	$matches = $matches[0];
	
	foreach($matches as $match) {
		$text = str_replace('{', '', $match);
		$text = str_replace('}', '', $text);
		
		
		$sql = "SELECT `content_id` FROM `cn_content` WHERE `content_title` LIKE ";
		$function = 'buildContentPermalink';
		
		if(strstr($text, ':')) {
			$split = explode(':', $text);
			switch($split[0]) {
				case 'tag':
					$sql = "SELECT `tag_id` FROM `cn_tags` WHERE `tag_title` LIKE ";
					$function = 'buildTagPermalink';
					break;
				case 'type':
					$sql = "SELECT `ct_id` FROM `cn_content_types` WHERE `ct_title` LIKE ";
					$function = 'buildTypePermalink';
					break;
			}
			$text = $split[1];
		}
		
		if(strstr($text, '|')) {
			$split = explode('|', $text);
			$text = $split[0];
			$linkText = $split[1];
		}
		
		else {
			$linkText = $text;
		}
		
		$id = DB()->getVar($sql . "'".$text."'");
		if($id) {
			$permalink = \application\system\Permalink::$function($id);
			$html = str_replace($match, '<a href="'.$permalink.'">'.$linkText.'</a>', $html);
		}
		else {
			$html = str_replace($match, '<a href="#" style="color:#920000;">'.$linkText.'</a>', $html);
		}
	}
	
	return $html;
}

?>